"""
# Modify such files as los_config.mk, test.mk, Kconfig according to lwip selection when making Version using python2 on Linux.
# Also upon your selection, documents in doc, folders in net and test/sample shall be deleted.
# Usage:
#     e.g. python2 lwip_select.py
#     input :1 for lwip1.4 selection, changes as follows:
#            build/mk/los_config.mk                  --modified
#            test/test.mk                            --modified
#            net/Kconfig                             --modified
#            doc/xxxlwIP-2.0xxx                      --deleted
#            net/lwip-2.0                            --deleted
#            test/sample/lwip-2.0                    --deleted
#            test/sample/lwip2.0_linux_CI            --deleted
#
#     input :2 for lwip2.0 selection, changes as follows:
#            build/mk/los_config.mk                  --modified
#            test/test.mk                            --modified
#            net/Kconfig                             --modified
#            doc/xxxlwIP-1.4xxx                      --deleted
#            net/lwip_sack                           --deleted
#            test/sample/lwip                        --deleted
#
#     input :3 for restoring files, changes as follows:
#            build/mk/los_config.mk                  --modified
#            test/test.mk                            --modified
#            net/Kconfig                             --modified
#
# Notice:
#     After run this script with input '1' or '2', only '3' input can be executed.
#     '3' input only restores los_config.mk, test.mk, Kconfig files to the same as mainline's, the files and folders
#     deleted should be added manually.
#     You should restore to mainline verison based on lwip1.4 version.
"""

import sys
import shutil
import os

los_config_path = "../../build/mk/"#los_config.mk
test_path = "../../test/"#test.mk
kconfig_path = "../../net/"#Kconfig

target_str = "LOSCFG_NET_LWIP_SACK_2_0"
unrun_str = "lwip1.4 text"

#replace_str = "lwip_version_2.0"

argv_str = ["LOSCFG_NET_LWIP_SACK_1_4", "LOSCFG_NET_LWIP_SACK_2_0"]
version_str = ["1.4", "2.0"]
note_str = [
"""unrun_str = "lwip1.4 text"
""",
"""unrun_str = "lwip2.0 text"
""",
"""unrun_str = "Original text"
"""]

config_replace_content = \
"""# LOSCFG_NET_LWIP_SACK_1_4 is not set
LOSCFG_NET_LWIP_SACK_2_0=y
"""

los_config_content = \
"""ifeq ($(LOSCFG_NET_LWIP_SACK_2_0), y)
    LITEOS_BASELIB += -llwip
    LIB_SUBDIRS       += net/lwip-2.0
    LITEOS_LWIP_SACK_INCLUDE   += \\
        -I $(LITEOSTOPDIR)/net/lwip-2.0/include \\
        -I $(LITEOSTOPDIR)/net/mac
    LWIP_MACROS += -DLWIP_CONFIG_FILE=\\"lwip/lwipopts.h\\"
    LITEOS_CMACRO     +=  $(LWIP_MACROS)
else
    LITEOS_BASELIB += -llwip
    LIB_SUBDIRS       += net/lwip_sack
    LITEOS_LWIP_SACK_INCLUDE   += \\
        -I $(LITEOSTOPDIR)/net/lwip_sack/include \\
        -I $(LITEOSTOPDIR)/net/lwip_sack/include/ipv4 \\
        -I $(LITEOSTOPDIR)/net/mac

    LITEOS_CMACRO     +=  $(LWIP_MACROS)
endif
"""

test_content = \
"""ifeq ($(LOSCFG_NET_LWIP_SACK_2_0), y)
    LIB_SUBDIRS    += test/sample/lwip-2.0
else
    LIB_SUBDIRS    += test/sample/lwip
endif
"""

kconfig_content = \
"""choice
    depends on LOSCFG_NET_LWIP_SACK
    prompt "Lwipsack"
    default y
    help
      Enable Lwipsack for 1.4
      Enable Lwipsack for 2.0

config LOSCFG_NET_LWIP_SACK_1_4
    bool "Enable Lwipsack (1.4)"
    depends on LOSCFG_NET_LWIP_SACK

config LOSCFG_NET_LWIP_SACK_2_0
    bool "Enable Lwipsack (2.0)"
    depends on LOSCFG_NET_LWIP_SACK

endchoice
"""

astr='\t\n\t\n'

def replace(replace_str, target_path, filename):

    target_file = target_path + filename
    file_data = ""
    new_file = target_file + "backup"

    try:
        with open(target_file, "r") as f:
            target_find = False
            target_branch = False
            for line in f:
                if target_str in line:
                    line = line.replace(target_str,replace_str)
                    target_find =True
                    file_data += line
                    target_branch = False  #each time find, init target branch

                    if target_str == replace_str:
                        target_branch = True
                    continue

                if target_find == True:
                    if target_str != replace_str:
                        if "else" in line:
                            target_branch = True
                            continue

                        if "endif" in line:
                            target_find = False
                            target_branch = True
                        if target_branch == False:
                            continue
                    else:
                        if "else" in line:
                            target_branch = False
                        if "endif" in line:
                            target_find = False
                            target_branch = True
                        if target_branch == False:
                            continue

                file_data += line
    except Exception as e:
        print "No such file %s" % target_file
        return e

    with open(new_file,"w") as f:
        f.write(file_data)
        f.close()
    shutil.move(new_file, target_file)


def delete(num, target_path, filename):
    replace_str = argv_str[num]
    target_file = target_path + filename
    file_data = ""
    new_file = target_file + "backup"

    try:
        with open(target_file, "r") as f:
            target_branch = False
            delete_branch = False
            choice_find = False
            depend_find = False

            for line in f:
                if "choice" in line:
                    choice_find = True
                    target_branch = False
                    delete_branch = False
                    depend_find = False

                if choice_find == True:
                    if "help" in line:
                        depend_find = True
                        file_data += line
                        continue

                    if "config" in line:
                        depend_find = False

                    if depend_find == True:
                        if line.strip() == "":#version_str[0] not in line and version_str[1] not in line:
                            pass
                        elif version_str[num] not in line:
                            continue
                        else:
                            pass

                    if "config" in line:
                        if replace_str in line:
                            target_branch = True
                        else:
                            delete_branch = True

                    if delete_branch == True:
                        if line.strip() == "":
                            delete_branch = False
                        else:
                            pass
                        continue

                    if "endchoice" in line:
                        choice_find = False
                file_data += line
    except Exception as e:
        print "No such file %s" % target_file
        return e

    with open(new_file,"w") as f:
        f.write(file_data)
        f.close()

    shutil.move(new_file, target_file)

def restore(target_path, filename):
    target_file = target_path + filename
    file_data = ""
    new_file = target_file + "backup"
    begin_str = ""
    end_str = ""
    if filename == "Kconfig":
        begin_str = "choice"
        end_str = "endchoice"
        original_content = kconfig_content
    elif filename == "los_config.mk":
        begin_str = "ifeq ($(LOSCFG_NET_LWIP_SACK_"
        end_str = "endif"
        original_content = los_config_content
    elif filename == "test.mk":
        begin_str = "ifeq ($(LOSCFG_NET_LWIP_SACK_"
        end_str = "endif"
        original_content = test_content
    else:
        print "No such file"
        return

    try:
        with open(target_file, "r") as f:
            target_find = False
            for line in f:
                if begin_str in line and target_find == False:
                    target_find = True
                    file_data += original_content
                if target_find == True:
                    if end_str in line:
                        target_find =False
                    continue

                file_data += line
    except Exception as e:
        print "No such file %s" % target_file
        return e

    with open(new_file,"w") as f:

        f.write(file_data)
        f.close()

    shutil.move(new_file, target_file)

def removeFiles(target_path, target_str):
    try:
        files = os.listdir(target_path)

        for i, f in enumerate(files):
            if f.find(target_str) >= 0:
                os.remove(target_path+f)
    except Exception as e:
        print "No such folder %s" % target_path
        return e

def update_text(num):
    file_data = ""
    new_file =  "lwip_selectbackup.py"
    target_file = "lwip_select.py"
    try:
        with open(target_file, "r") as f:
            for line in f:
                if line.startswith("unrun_str"):
                    file_data += note_str[num]
                    continue
                file_data += line
    except Exception as e:
        print "No such file %s" % target_file
        return e

    with open(new_file,"w") as f:

        f.write(file_data)
        f.close()

    shutil.move(new_file, target_file)

def batch_modify(target_path, target_str):
    try:
        files = os.listdir(target_path)

        for i, f in enumerate(files):
            if f.find(target_str) >= 0:
                #os.remove(target_path+f)
                target_file = target_path + f
                file_data = ""
                new_file = target_file + "backup"
                begin_str = "LOSCFG_NET_LWIP_SACK_1_4"
                end_str = "LOSCFG_NET_LWIP_SACK_2_0"
                original_content = config_replace_content
                try:
                    with open(target_file, "r") as f:
                        target_find = False
                        for line in f:
                            if begin_str in line and target_find == False:
                                target_find = True
                                file_data += original_content
                            if target_find == True:
                                if end_str in line:
                                    target_find =False
                                continue

                            file_data += line
                except Exception as e:
                    print "No such file %s" % target_file
                    return e

                with open(new_file,"w") as f:

                    f.write(file_data)
                    f.close()

                shutil.move(new_file, target_file)


    except Exception as e:
        print "No such folder %s" % target_path
        return e




if __name__=='__main__':

    print "1 is for lwip1.4"
    print "2 is for lwip2.0"
    print "3 is to restore files to the same as mainline"

    num = raw_input("input:")

    assert(len(num) == 1)
    assert(int(num) == 1 or int(num) == 2 or int(num) == 3)

    if num == '1':
        if unrun_str != "Original text":
            print "cannot execute, not original files"
            sys.exit()

        print "You select lwip1.4 to make"
        replace(argv_str[0],los_config_path, "los_config.mk")
        replace(argv_str[0],test_path, "test.mk")
        delete(int(num)-1,kconfig_path, "Kconfig")
        removeFiles("../../doc/", "lwIP-2.0")
        shutil.rmtree("../../net/lwip-2.0")
        shutil.rmtree("../../test/sample/lwip-2.0")
        shutil.rmtree("../../test/sample/lwip2.0_linux_CI")
    elif num == "2":
        if unrun_str != "Original text":
            print "cannot execute, not original files"
            sys.exit()

        print "You select lwip2.0 to make"
        replace(argv_str[1],los_config_path, "los_config.mk")
        replace(argv_str[1],test_path, "test.mk")
        delete(int(num)-1,kconfig_path, "Kconfig")
        removeFiles("../../doc/", "lwIP-1.4")
        shutil.rmtree("../../net/lwip_sack")
        shutil.rmtree("../../test/sample/lwip")
        batch_modify("../build/config/","config")
        batch_modify("../build/config/debug/","config")
        batch_modify("../build/config/testsuit/","config")
    else:
        if unrun_str == "Original text":
            print "cannot execute, original files"
            sys.exit()

        print "You select to restore files to the same as mainline"
        restore(los_config_path, "los_config.mk")
        restore(test_path, "test.mk")
        restore(kconfig_path, "Kconfig")

    update_text(int(num)-1)
    print "modify end"


